package org.jeecg.modules.controller;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.RandomUtils;

import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;

import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.RedisUtil;

import org.jeecg.modules.entity.DiyProfessorInfo;
import org.jeecg.modules.entity.DiyProjectOwnProfessorType;
import org.jeecg.modules.entity.DiyProjectProfessor;
import org.jeecg.modules.entity.ProjectProfessorInfo;
import org.jeecg.modules.mapper.DiyProfessorInfoMapper;
import org.jeecg.modules.service.IDiyProfessorInfoService;
import org.jeecg.modules.service.IDiyProjectOwnProfessorTypeService;
import org.jeecg.modules.service.IDiyProjectProfessorService;
import org.jeecg.modules.service.IProjectProfessorInfoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.vo.ProjectProfessorStar;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.vo.SelectForEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 项目所需专家抽取状态
 * @Author: jeecg-boot
 * @Date: 2020-07-06
 * @Version: V1.0
 */
@Api(tags = "项目所需专家抽取状态")
@RestController
@RequestMapping("/projectProfessorInfo")
@Slf4j
public class ProjectProfessorInfoController extends JeecgController<ProjectProfessorInfo, IProjectProfessorInfoService> {
    @Autowired
    private IProjectProfessorInfoService projectProfessorInfoService;
    @Autowired
    private IDiyProfessorInfoService professorInfoService;
    @Autowired
    private IDiyProjectProfessorService projectProfessorService;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiyProfessorInfoMapper diyProfessorInfoMapper;
    @Autowired
    private IDiyProjectOwnProfessorTypeService diyProjectOwnProfessorTypeService;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * 分页列表查询
     *
     * @param projectProfessorInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "项目所需专家抽取状态-分页列表查询")
    @ApiOperation(value = "项目所需专家抽取状态-分页列表查询", notes = "项目所需专家抽取状态-分页列表查询")
    @GetMapping(value = "/list2")
    public Result<?> queryPageList(ProjectProfessorInfo projectProfessorInfo,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
//        System.out.println(projectProfessorInfo);
//        String date = req.getParameter("date");
//        System.out.println(date);
        QueryWrapper<ProjectProfessorInfo> queryWrapper = QueryGenerator.initQueryWrapper(projectProfessorInfo, req.getParameterMap());
        Page<ProjectProfessorInfo> page = new Page<>(pageNo, pageSize);
        IPage<ProjectProfessorInfo> pageList = projectProfessorInfoService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    @AutoLog(value = "项目所需专家抽取状态-分页列表查询")
    @ApiOperation(value = "项目所需专家抽取状态-分页列表查询", notes = "项目所需专家抽取状态-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList2(SelectForEntity selectForEntity,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    HttpServletRequest req) {

//        System.out.println(selectForEntity);

        Page<ProjectProfessorInfo> page = new Page<>(pageNo, pageSize);
        IPage<ProjectProfessorInfo> pageList = projectProfessorInfoService.pageByEntity(page, selectForEntity);
        return Result.ok(pageList);
    }

    /**
     * 紧急请假根据专家id查询
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping(value = "/listByProfessorId")
    public Result<?> listByProfessorId(
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<ProjectProfessorInfo> page = new Page<>(pageNo, pageSize);
        // 获取当前操作的用户信息
        Subject subject = SecurityUtils.getSubject();
        LoginUser user = (LoginUser) subject.getPrincipal();
        IPage<ProjectProfessorInfo> pageList = null;
        if (user!=null){
            pageList = projectProfessorInfoService.pageByProfessorUserId(page,user);
        }
        return Result.ok(pageList);
    }
    @GetMapping(value = "/listByProfessorId01")
    public Result<?> listByProfessorId01(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<ProjectProfessorInfo> page = new Page<>(pageNo, pageSize);
        // 获取当前操作的用户信息
        Subject subject = SecurityUtils.getSubject();
        LoginUser user = (LoginUser) subject.getPrincipal();
        IPage<ProjectProfessorInfo> pageList = null;
        if (user!=null){
            pageList = projectProfessorInfoService.pageByProfessorUserId01(page,user);
        }
        return Result.ok(pageList);
    }

    @PostMapping(value = "/listByProfessorId03")
    public Result<?> listByProfessorId03(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestBody JSONObject jsonObject) {
        String projectName = jsonObject.getString("projectName");
        Page<ProjectProfessorInfo> page = new Page<>(pageNo, pageSize);
        // 获取当前操作的用户信息
        Subject subject = SecurityUtils.getSubject();
        LoginUser user = (LoginUser) subject.getPrincipal();
        IPage<ProjectProfessorInfo> pageList = null;
            if (user != null) {
                pageList = projectProfessorInfoService.pageByProfessorUserId03(page, user, projectName);
            }
                return Result.ok(pageList);
    }
    /**
     * 添加
     *
     * @param projectProfessorInfo
     * @return
     */
    @AutoLog(value = "项目所需专家抽取状态-添加")
    @ApiOperation(value = "项目所需专家抽取状态-添加", notes = "项目所需专家抽取状态-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ProjectProfessorInfo projectProfessorInfo) {
        projectProfessorInfo.setProjectStatus(ProjectProfessorInfo.projectStage.BEGIN);
        projectProfessorInfoService.save(projectProfessorInfo);
        for (int i = 0; i < projectProfessorInfo.getProjectOwnProfessorType().size(); i++) {
            DiyProjectOwnProfessorType projectOwnProfessorType = projectProfessorInfo.getProjectOwnProfessorType().get(i);
            projectOwnProfessorType.setNeedProfessorNumber(projectOwnProfessorType.getProfessorNumber());
            projectOwnProfessorType.setProjectId(projectProfessorInfo.getId());
            projectOwnProfessorType.setThinkProfessorNumber("0");
            projectOwnProfessorType.setIsSave("true");
            projectOwnProfessorType.setId(null);
            diyProjectOwnProfessorTypeService.save(projectOwnProfessorType);
        }
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param projectProfessorInfo
     * @return
     */
    @AutoLog(value = "项目所需专家抽取状态-编辑")
    @ApiOperation(value = "项目所需专家抽取状态-编辑", notes = "项目所需专家抽取状态-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ProjectProfessorInfo projectProfessorInfo) {
        //先保存修改的基本信息（不包括专家类型和人数)
        projectProfessorInfoService.updateById(projectProfessorInfo);
        //查询该项目未修改前对应的专家类型数据
        List<DiyProjectOwnProfessorType> list = diyProjectOwnProfessorTypeService.list(new QueryWrapper<DiyProjectOwnProfessorType>().lambda().
                eq(DiyProjectOwnProfessorType::getProjectId, projectProfessorInfo.getId()));
        diyProjectOwnProfessorTypeService.remove(new QueryWrapper<DiyProjectOwnProfessorType>().lambda().
                eq(DiyProjectOwnProfessorType::getProjectId, projectProfessorInfo.getId()));
        //更新专家类型和对应的人数
        for (int i = 0; i < projectProfessorInfo.getProjectOwnProfessorType().size(); i++) {

            DiyProjectOwnProfessorType projectOwnProfessorType = new DiyProjectOwnProfessorType();

//            Map<String, String> map = (Map) projectProfessorInfo.getProjectOwnProfessorType().get(i);
            //项目中的一条专家类型信息
            DiyProjectOwnProfessorType projectOwnProfessorTypeOne = projectProfessorInfo.getProjectOwnProfessorType().get(i);
            projectOwnProfessorType.setProfessorType(projectOwnProfessorTypeOne.getProfessorType());
            projectOwnProfessorType.setProjectId(projectProfessorInfo.getId());
            projectOwnProfessorType.setProfessorTypeName(projectOwnProfessorTypeOne.getProfessorTypeName());
            projectOwnProfessorType.setEditable(projectOwnProfessorTypeOne.getEditable());
            projectOwnProfessorType.setIsNew(projectOwnProfessorTypeOne.getIsNew());
            projectOwnProfessorType.setIsSave("true");


            for (int j = 0; j < list.size(); j++) {
                if (list.get(j).getProfessorType().equals(projectOwnProfessorTypeOne.getProfessorType())) {
                    projectOwnProfessorType.setThinkProfessorNumber(list.get(i).getThinkProfessorNumber());

                    //判断保存的专家类型对应的人数是否更改,未更改直接更新目前所需要的人数即可
                    if (list.get(j).getProfessorNumber().equals(projectOwnProfessorTypeOne.getProfessorNumber())) {
                        projectOwnProfessorType.setProfessorNumber(projectOwnProfessorTypeOne.getProfessorNumber());
                        projectOwnProfessorType.setNeedProfessorNumber(list.get(i).getNeedProfessorNumber());
                        diyProjectOwnProfessorTypeService.save(projectOwnProfessorType);
                    } else {
                        //更改后需要更新现在总共需要的人数，并且重新计算目前所需要人数
                        int originalNum = Integer.parseInt(list.get(j).getProfessorNumber());
                        int newNum = Integer.parseInt(projectOwnProfessorTypeOne.getProfessorNumber());
                        if (newNum < 0) {
                            return Result.error("人数不能为负值，请正确操作！");
                        } else if (newNum > originalNum) {
                            return Result.error("专家类型的人数只能比原来少，请减少人数!");

                        }
                        int nowNum = Integer.parseInt(list.get(i).getNeedProfessorNumber()) - (originalNum - newNum);
                        if (nowNum < 0) {
                            return Result.error("已经有专家同意审批，请不要过度减少人数!");
                        }
                        projectOwnProfessorType.setProfessorNumber(projectOwnProfessorTypeOne.getProfessorNumber());
                        projectOwnProfessorType.setNeedProfessorNumber(Integer.toString(nowNum));
                        diyProjectOwnProfessorTypeService.save(projectOwnProfessorType);
                    }
                    break;
                }

            }
            if (i > list.size() || i == list.size()) {
                projectOwnProfessorType.setIsSave("true");

                projectOwnProfessorType.setThinkProfessorNumber("0");
                projectOwnProfessorType.setProfessorNumber(projectOwnProfessorTypeOne.getProfessorNumber());
                projectOwnProfessorType.setNeedProfessorNumber(projectOwnProfessorTypeOne.getProfessorNumber());
                diyProjectOwnProfessorTypeService.save(projectOwnProfessorType);
            }
        }

        //查询更改后是否达到项目状态改变的条件(即所有专家类型所需的人数为零)
        List<DiyProjectOwnProfessorType> projectOwnProfessorTypeList = diyProjectOwnProfessorTypeService.list(new QueryWrapper<DiyProjectOwnProfessorType>()
                .lambda().eq(DiyProjectOwnProfessorType::getProjectId, projectProfessorInfo.getId()));
        int finish = 0;
        for (DiyProjectOwnProfessorType projectOwnProfessorType : projectOwnProfessorTypeList) {
            if ((Integer.parseInt(projectOwnProfessorType.getNeedProfessorNumber()) == 0)) {
                finish++;
            }
        }
        if (finish == projectOwnProfessorTypeList.size()) {
            //全部同意将项目变为完成状态
            UpdateWrapper<ProjectProfessorInfo> updateWrapper2 = new UpdateWrapper<>();

                updateWrapper2.eq("id", projectProfessorInfo.getId()).set("project_status", ProjectProfessorInfo.projectStage.FINISH);

            projectProfessorInfoService.update(null, updateWrapper2);
        }else{
            UpdateWrapper<ProjectProfessorInfo> updateWrapper2 = new UpdateWrapper<>();
            updateWrapper2.eq("id", projectProfessorInfo.getId()).set("project_status", ProjectProfessorInfo.projectStage.WAIT);
        }
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目所需专家抽取状态-通过id删除")
    @ApiOperation(value = "项目所需专家抽取状态-通过id删除", notes = "项目所需专家抽取状态-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        projectProfessorInfoService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "项目所需专家抽取状态-批量删除")
    @ApiOperation(value = "项目所需专家抽取状态-批量删除", notes = "项目所需专家抽取状态-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.projectProfessorInfoService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目所需专家抽取状态-通过id查询")
    @ApiOperation(value = "项目所需专家抽取状态-通过id查询", notes = "项目所需专家抽取状态-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ProjectProfessorInfo projectProfessorInfo = projectProfessorInfoService.getById(id);
        if (projectProfessorInfo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(projectProfessorInfo);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param projectProfessorInfo
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ProjectProfessorInfo projectProfessorInfo) {
        return super.exportXls(request, projectProfessorInfo, ProjectProfessorInfo.class, "项目所需专家抽取状态");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ProjectProfessorInfo.class);
    }

    /**
     * 批量抽取专家
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "根据项目类型抽取专家，抽取之后不给专家推送消息等待管理员确认")
    @ApiOperation(value = "专家随机抽取，不推送", notes = "专家随机抽取，不推送")
    @DeleteMapping(value = "/randomChoose")
    public Result<?> randomChoose(@RequestParam(name = "ids", required = true) String ids, HttpServletRequest request) {
        System.out.println(ids);
        //项目id
        String id = ids;
        //该项目的全部信息
        ProjectProfessorInfo projectInfo = projectProfessorInfoService.getById(id);
        //更新项目的状态为：WAIT
        projectInfo.setProjectStatus(ProjectProfessorInfo.projectStage.WAIT);
        projectProfessorInfoService.updateById(projectInfo);

        //用来记录项目中人数不够的专家类型
        List<String> errorList = new ArrayList<>();


        //该项目的专家类型集合
        List<DiyProjectOwnProfessorType> projectProfessorTypeList = diyProjectOwnProfessorTypeService.list(new QueryWrapper<DiyProjectOwnProfessorType>().
                lambda().
                eq(DiyProjectOwnProfessorType::getProjectId, id));

        for (DiyProjectOwnProfessorType projectOwnProfessorType : projectProfessorTypeList) {
            //判断该类型抽取的专家人数是否已经达到要求
            if (Integer.parseInt(projectOwnProfessorType.getProfessorNumber()) !=
                    Integer.parseInt(projectOwnProfessorType.getThinkProfessorNumber()) && Integer.parseInt(projectOwnProfessorType.getNeedProfessorNumber()) != 0) {
                //查询项目中已经存在的专家id
                List<DiyProjectProfessor> list = projectProfessorService.list(new QueryWrapper<DiyProjectProfessor>().lambda().
                        eq(DiyProjectProfessor::getProjectId, id));
                //项目中已经存在的专家id集合
                List<String> projectOwnUserId = new ArrayList<>();

                for (DiyProjectProfessor diyProjectProfessor : list) {
                    projectOwnUserId.add(diyProjectProfessor.getDingUserId());
                }
                //查询所有专家信息
                QueryWrapper<DiyProfessorInfo> wrapper1 = Wrappers.query();
                //筛选未请假和未参加项目的专家,并且不再该项目中的专家
                if (projectOwnUserId.size() > 0) {
                    wrapper1.eq("is_leave", 0).eq("is_work", 0).
                            eq("is_change_info",0).notIn("ding_user_id", projectOwnUserId);
                } else {
                    wrapper1.eq("is_leave", 0).eq("is_work", 0).eq("is_change_info",0);
                }
                List<DiyProfessorInfo> professorList = professorInfoService.list(wrapper1);

                //对专家进行筛选满足该项目类型的专家抽取出来
                List<String> currentTypeProfessorList = new ArrayList<>();
                for (DiyProfessorInfo dp : professorList) {
                    //该专家的专家类型集合
                    String[] split = dp.getProfessorDeclareCategory().split(",");
                    for (int j = 0; j < split.length; j++) {
                        //判断专家类型和项目类型是否一致
                        if (projectOwnProfessorType.getProfessorType().equals(split[j])) {
                            currentTypeProfessorList.add(dp.getDingUserId());
                        }
                    }
                }
                int thinkNum = 0;
                //专家库人数不足给
                if (currentTypeProfessorList.size() < Integer.parseInt(projectOwnProfessorType.getProfessorNumber()) ||
                        currentTypeProfessorList.size() == Integer.parseInt(projectOwnProfessorType.getProfessorNumber())) {
                    if (currentTypeProfessorList.size() < Integer.parseInt(projectOwnProfessorType.getProfessorNumber())) {
                        //记录项目名称
                        errorList.add(projectInfo.getProjectName() + "项目中");
                        //记录不足的人数和相关信息
                        errorList.add(projectOwnProfessorType.getProfessorTypeName() + "人数不足" + projectOwnProfessorType.getNeedProfessorNumber()
                                + "人，系统目前拥有：" + currentTypeProfessorList.size() + "人，请减少该类型对应的人数或者增加其他类型");
                        projectProfessorInfoService.update(null, new UpdateWrapper<ProjectProfessorInfo>().lambda().
                                eq(ProjectProfessorInfo::getId, id).set(ProjectProfessorInfo::getProjectStatus, ProjectProfessorInfo.projectStage.WARN));
                        thinkNum = Integer.parseInt(projectOwnProfessorType.getProfessorNumber()) - currentTypeProfessorList.size();
                    } else {
                        thinkNum = Integer.parseInt(projectOwnProfessorType.getProfessorNumber());
                    }
                    //直接给抽取到的人发送邀请，人数不足无需抽取
                    for (int j = 0; j < currentTypeProfessorList.size(); j++) {
                        DiyProjectProfessor projectProfessor = new DiyProjectProfessor();
                        projectProfessor.setDingUserId((String) currentTypeProfessorList.get(j));
                        projectProfessor.setProjectId(id);
                        projectProfessor.setProfessorInProjectStates(-1);
                        projectProfessor.setProfessorInProjectProfessorType(projectOwnProfessorType.getProfessorType());
                        projectProfessorService.save(projectProfessor);
                        //被系统选中，考虑中人数加一
                        projectProfessorInfoService.thinkNumberReduce(id,projectOwnProfessorType.getProfessorType(),1);
                    }


                } else {
                    //进行随机抽取
                    //如果库存中专家人数超过需要的专家数目，则进行随机抽取
                    int[] indexArray = new int[Integer.parseInt(projectOwnProfessorType.getNeedProfessorNumber())];
                    for (int i = 0; i < indexArray.length; i++) {
                        indexArray[i]-=1;
                    }
                    for (int i = 0; i < indexArray.length; ) {
                        int random = RandomUtils.nextInt(0, currentTypeProfessorList.size());
                        boolean flag = false;
                        for (int x : indexArray) {//产生的随机数和数组中的数据全部进行比较
                            if (x == random) {//如果存在就跳出
                                flag = false;
                                break;
                            } else {//否则一直比较下去
                                flag = true;
                            }
                        }

                        if (flag) {
                            indexArray[i++] = random;
                        }
                    }

                    for (int k = 0; k < Integer.parseInt(projectOwnProfessorType.getNeedProfessorNumber()); k++) {
                        DiyProjectProfessor projectProfessor = new DiyProjectProfessor();
                        projectProfessor.setDingUserId((String) currentTypeProfessorList.get(indexArray[k]));
                        projectProfessor.setProjectId(id);
                        projectProfessor.setProfessorInProjectStates(-1);
                        projectProfessor.setProfessorInProjectProfessorType(projectOwnProfessorType.getProfessorType());
                        projectProfessorService.save(projectProfessor);
                        //被系统选中，考虑中人数加一
                        projectProfessorInfoService.thinkNumberReduce(id,projectOwnProfessorType.getProfessorType(),1);
                    }
                }

            } else {
                //需要的专家人数和正在抽取的专家人数相等不需要抽取
            }

        }
        HttpHeaders requestHeaders = new HttpHeaders();
        String token = request.getHeader("X-Access-Token");
        requestHeaders.add("X-Access-Token", token);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, requestHeaders);
        String url = "http://312730ua54.51vip.biz" + request.getContextPath() + "/sendAdminErrorList/" + errorList;
        System.out.println(url);
        ResponseEntity<Result> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Result.class);
        Result result = responseEntity.getBody();
        return Result.ok("请到抽取详情页面查看抽取结果!");
    }

    @AutoLog(value = "项目所需专家抽取状态-抽取指定类型的专家")
    @ApiOperation(value = "项目所需专家抽取状态-抽取指定类型的专家", notes = "项目所需专家抽取状态-抽取指定类型的专家")
    @RequestMapping(value = "/randomOneChoose/{id}/{dingUserId}/{originator_userid}/{isSend}")
    public Result<?> randomOneChoose(@PathVariable("id") String id, HttpServletRequest request,
                                     @PathVariable("dingUserId") String dingUserId,
                                     @PathVariable("originator_userid") String originator_userid, @PathVariable("isSend") boolean isSend) {

        //获取该项目的详细信息
        ProjectProfessorInfo projectInfo = projectProfessorInfoService.getById(id);

        List<String> professorList = new ArrayList<>();
        //查询拒接项目的专家在项目中的专家类型
        QueryWrapper<DiyProjectProfessor> wrapper = Wrappers.query();
        wrapper.eq("project_id", id).eq("ding_user_id", dingUserId);
        List<DiyProjectProfessor> one = projectProfessorService.list(wrapper);
        //获取拒绝项目的专家对应项目中的专家类型
        String professorType = projectProfessorService.getOne(wrapper).getProfessorInProjectProfessorType();
        //对上次拒接的专家所对应的专家类型抽取中人数减一
        projectProfessorInfoService.thinkNumberReduce(id,professorType,-1);
        //将此专家对应的项目专家类型的抽取中人数减一(暂不操作)
        DiyProjectOwnProfessorType one2 = diyProjectOwnProfessorTypeService.getOne(new QueryWrapper<DiyProjectOwnProfessorType>().lambda().
                eq(DiyProjectOwnProfessorType::getProjectId, id).eq(DiyProjectOwnProfessorType::getProfessorType, professorType));

        //查询该项目下所有专家
        QueryWrapper<DiyProjectProfessor> wrapper2 = Wrappers.query();
        wrapper2.eq("project_id", id);
        List<DiyProjectProfessor> list2 = projectProfessorService.list(wrapper2);
        List<String> excludeId = new ArrayList<>();
        for (DiyProjectProfessor diyProjectProfessor : list2) {
            excludeId.add(diyProjectProfessor.getDingUserId());
        }
        List<DiyProfessorInfo> list;
        if (excludeId.size() > 0) {
            //排除项目中已经存在的转件
            QueryWrapper<DiyProfessorInfo> wrapper1 = Wrappers.query();
            wrapper1.notIn("ding_user_id", excludeId).eq("is_leave", 0).
                    eq("is_work", 0).eq("is_change_info",0);
            list = professorInfoService.list(wrapper1);
        } else {
            QueryWrapper<DiyProfessorInfo> wrapper1 = Wrappers.query();
            wrapper1.eq("is_leave", 0).eq("is_change_info",0).
                    eq("is_work", 0).ne("ding_user_id", dingUserId);
            list = professorInfoService.list(wrapper1);
        }

        for (DiyProfessorInfo dp : list) {
            //该专家的专家类型集合
            String[] split = dp.getProfessorDeclareCategory().split(",");
            //判断专家类型和项目类型是否一致
            for (int i = 0; i < split.length; i++) {
                if (professorType.equals(split[i])) {
                    professorList.add(dp.getDingUserId());
                }
            }
        }
        List<String> errorList = new ArrayList<>();
        if (professorList.size() > 0) {
            //预备组中选取正式组，如果人数不够直接全部赋值，如果人数多于随机抽取
            //如果人数不够直接全部赋值
            for (int i = 0; i < professorList.size(); i++) {
                if (professorList.size() == 1) {
                    DiyProjectProfessor projectProfessor = new DiyProjectProfessor();
                    projectProfessor.setDingUserId((String) professorList.get(i));
                    projectProfessor.setProjectId(id);
                    projectProfessor.setProfessorInProjectStates(-1);
                    projectProfessor.setProfessorInProjectProfessorType(professorType);
                    projectProfessorService.save(projectProfessor);
                    //被系统选中，考虑中人数加一
                    projectProfessorInfoService.thinkNumberReduce(id,professorType,1);
                    UpdateWrapper<DiyProjectProfessor> updateWrapper = new UpdateWrapper<>();
                    //更新专家在该项目中的身份（项目中的专家类型）
                    updateWrapper.eq("project_id", id).
                            eq("ding_user_id", projectProfessor.getDingUserId()).
                            set("professor_in_project_professor_type", professorType);
                    projectProfessorService.update(null, updateWrapper);

                } else {


                    DiyProjectProfessor projectProfessor = new DiyProjectProfessor();
                    int random = RandomUtils.nextInt(0, professorList.size());
                    projectProfessor.setDingUserId((String) professorList.get(random));
                    projectProfessor.setProjectId(id);
                    projectProfessor.setProfessorInProjectProfessorType(professorType);
                    projectProfessor.setProfessorInProjectStates(-1);
                    projectProfessorService.save(projectProfessor);
                    //被系统选中，考虑中人数加一
                    projectProfessorInfoService.thinkNumberReduce(id,professorType,1);

                    UpdateWrapper<DiyProjectProfessor> updateWrapper = new UpdateWrapper<>();
                    //更新专家在该项目中的身份（项目中的专家类型）
                    updateWrapper.eq("project_id", id).
                            eq("ding_user_id", projectProfessor.getDingUserId()).
                            set("professor_in_project_professor_type", professorType);
                    break;
                }
            }
            HttpHeaders requestHeaders = new HttpHeaders();
            String token = request.getHeader("X-Access-Token");
            requestHeaders.add("X-Access-Token", token);

            redisUtil.set("originator_userid", originator_userid);
            if (isSend) {
                HttpEntity<String> requestEntity = new HttpEntity<>(null, requestHeaders);
                String url = "http://312730ua54.51vip.biz" + request.getContextPath() + "/sendProfessorChooseToDing/" + id;
                System.out.println(url);
                ResponseEntity<Result> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Result.class);
                Result result = responseEntity.getBody();
                return result;
            } else {
                return Result.ok("删除成功");
            }
        } else {
            //查询项目中该类型的详细信息
            DiyProjectOwnProfessorType one1 = diyProjectOwnProfessorTypeService.getOne(new QueryWrapper<DiyProjectOwnProfessorType>().
                    lambda().
                    eq(DiyProjectOwnProfessorType::getProjectId, id).
                    eq(DiyProjectOwnProfessorType::getProfessorType, professorType));
            errorList.add(projectInfo.getProjectName() + "项目中");
            errorList.add(one1.getProfessorTypeName() + "人数不足" + one1.getNeedProfessorNumber()
                    + "人，系统目前拥有：0人，请减少该类型对应的人数或者增加其他类型"
            );
            //专家库人数不足
            UpdateWrapper<ProjectProfessorInfo> updateWrapper1 = new UpdateWrapper<>();
            updateWrapper1.eq("id", id).set("project_status", ProjectProfessorInfo.projectStage.WARN);
            projectProfessorInfoService.update(null, updateWrapper1);
            HttpHeaders requestHeaders = new HttpHeaders();
            String token = request.getHeader("X-Access-Token");
            requestHeaders.add("X-Access-Token", token);
            redisUtil.set("originator_userid", originator_userid);
            //请求通知专家
            HttpEntity<String> requestEntity = new HttpEntity<>(null, requestHeaders);
            //发送人数不够通知
            String url = "http://312730ua54.51vip.biz" + request.getContextPath() + "/sendAdminErrorList/" + errorList;
            System.out.println(url);
            ResponseEntity<Result> responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Result.class);
            Result result = responseEntity.getBody();

            return result;
        }
    }

    @AutoLog(value = "查询当前项目所需的专家人数在库中是否满足")
    @ApiOperation(value = "查询当前项目所需的专家人数在库中是否满足", notes = "查询当前项目所需的专家人数在库中是否满足")
    @GetMapping(value = "/queryProfessorNumber/{id}")
    public Result<?> queryProfessorNumber(@PathVariable("id") String id) {
        //获取该项目的详细信息
        ProjectProfessorInfo projectInfo = projectProfessorInfoService.getById(id);
        //获取该项目需要的专家类型
        List<DiyProjectOwnProfessorType> projectProfessorTypeList = diyProjectOwnProfessorTypeService.list(new QueryWrapper<DiyProjectOwnProfessorType>().
                lambda().
                eq(DiyProjectOwnProfessorType::getProjectId, id));
        int[] flag = new int[projectProfessorTypeList.size()];
        //获得所有的专家
        List<DiyProfessorInfo> professorInfos = professorInfoService.list(new QueryWrapper<DiyProfessorInfo>().lambda().
                eq(DiyProfessorInfo::getIsLeave,0).eq(DiyProfessorInfo::getIsChangeInfo,0).eq(DiyProfessorInfo::getIsWork,0));
        for (DiyProfessorInfo professorInfo : professorInfos) {
            String[] oneProfessorOwnType = professorInfo.getProfessorDeclareCategory().split(",");
            for (int j = 0; j < projectProfessorTypeList.size(); j++) {
                for (int i = 0; i < oneProfessorOwnType.length; i++) {
                    if (oneProfessorOwnType[i].equals(projectProfessorTypeList.get(j).getProfessorType())) {
                        flag[j]++;
                    }
                }
            }
        }
        List<String> errorList = new ArrayList<>();
        for (int m = 0; m < projectProfessorTypeList.size(); m++) {
            if (flag[m] < Integer.parseInt(projectProfessorTypeList.get(m).getNeedProfessorNumber())) {
                errorList.add(projectProfessorTypeList.get(m).getProfessorTypeName() + "系统剩余人数" + flag[m] + "人");
            }
        }
        String errorMsg = "";

        for (int i = 0; i < errorList.size(); i++) {
            if (i == errorList.size() - 1) {
                errorMsg += errorList.get(i);
            } else {
                errorMsg += errorList.get(i) + ",";
            }
        }
        if (errorList.size() > 0) {
            return Result.error(errorMsg + ",人数不足请减少人数或者重新选择类型");
        } else {
            return Result.ok(true);
        }
    }


    @PostMapping("/updateComment")
    public Result<?> updateProjectAndProfessorComment(@RequestBody JSONObject jsonObject) {
        Result<T> result = new Result();
        log.info("接收到更新项目评分和专家评分操作 ==> {}", jsonObject);
        // 获取项目附件
        String files = jsonObject.getString("files");
        // 获取项目评价
        String comment = jsonObject.getString("comment");
        // 获取项目id
        String projectId = jsonObject.getString("projectId");
        // 获取参加该项目的专家集合
        List<ProjectProfessorStar> professors = new ArrayList<>();
        // jsonArray数组类型的专家集合
        JSONArray jsonArray = jsonObject.getJSONArray("professors");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            // 放入对象中保存信息
            ProjectProfessorStar info = new ProjectProfessorStar();
            info.setKey(obj.getString("key"));
            info.setValue(Integer.parseInt(obj.getString("value")));
            professors.add(info);
        }


        // 调用业务层 传入项目id，项目评价，参与者得分，根据项目id修改项目状态为OVER，已结束，
        try {
            projectProfessorInfoService.updateComment(projectId, comment, professors,files);
            result.setSuccess(true);
            result.setMessage("评价成功!");
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMessage("操作失败!");
            return result;
        }
    }
}
